<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
            <el-button type="primary" @click="clickAddRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表单 -->
      <el-table :data="rolesList" style="width: 100%" stripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['borderBottom',index1==0?'borderTop':'','navCen']" v-for="(item1,index1) in scope.row.children" :key="index1">
              <!-- 第一级权限 -->
              <el-col :span="5">
                <el-tag @close="closeTag(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 第二级权限 -->
              <el-col :span="19">
                <el-row :class="['navCen','borderBottom']" v-for="(item2,index2) in item1.children" :key="index2">
                  <el-col :span="6">
                    <el-tag @close="closeTag(scope.row,item2.id)" closable type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag style="margin:5px 7px" @close="closeTag(scope.row,item3.id)" closable type="warning" v-for="(item3,index3) in item2.children" :key="index3">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
              
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
             <template slot-scope="scope">
                <!-- 编辑 -->
                <el-tooltip effect="dark" content="编辑" placement="top-start" :enterable="false">
                    <el-button type="primary" size="mini" @click="editRole(scope.row)"><i class="el-icon-edit"></i> 编辑</el-button>
                </el-tooltip>
                 <!-- 删除 -->
                 <el-tooltip effect="dark" content="删除" placement="top-start" :enterable="false">
                    <el-button type="danger" size="mini" @click="deleteRole(scope.row.id)"><i class="el-icon-delete"></i> 删除</el-button>
                </el-tooltip>
                 <!-- 分配权限 -->
                 <el-tooltip effect="dark" content="分配权限" placement="top-start" :enterable="false">
                    <el-button @click="clickSettingDialog(scope.row)" type="warning" size="mini"><i class="el-icon-setting"></i> 分配权限</el-button>
                 </el-tooltip>
            </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限dialog -->
    <el-dialog
      title="提示"
      :visible.sync="settingDialog"
      width="50%"
      @close="settingDialogClose"
      >
      <!-- <span>这是一段信息</span> -->
      <el-tree :data="rightsList" :props="defaultProps" show-checkbox node-key='id' default-expand-all
       :default-checked-keys='defKeys'
       ref="treeRef"	
       ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingDialog = false">取 消</el-button>
        <el-button type="primary" @click="sllotRingts">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色dialog -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialog"
      width="50%"
      @close="closeAddRoleDialog"
      >
      <el-form ref="addRole" :model="addRoleForm" :rules="roleRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRoleForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色dialog -->
    <el-dialog
      title="添加角色"
      :visible.sync="editRoleDialog"
      width="50%"
      @close="closeEditDialog"
      >
      <el-form ref="editRole" :model="roleInfo" :rules="roleRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleInfo.roleName"></el-input>
        </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRole">确 定</el-button>
      </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList:[],
      rightsList:[],
      settingDialog:false,
      addRoleDialog:false,
      editRoleDialog:false,
      roleInfo:{},
      addRoleForm:{
        roleName:'',
        roleDesc:''
      },
      roleRules:{
        roleName:[
           { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc:[
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ]
      },
      defaultProps:{
          children: 'children',
          label: 'authName'
      },
      //默认选中权限
      defKeys:[],
      roleId:0
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取角色列表
    async getRolesList(){
      var {data:res}=await this.$http.get('roles');
      if(res.meta.status!==200) return this.$message.error('获取角色列表数据失败')
      this.rolesList=res.data;
      console.log(this.rolesList)
    },
    //删除权限
    async closeTag(role,id){
      var resConfirm=await this.$confirm('此操作将该用户权限删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(resConfirm!=='confirm'){
          return this.$message.info('取消了删除')
        }
        console.log(resConfirm)
        //发送请求删除权限
       var {data:res}=await this.$http.delete(`roles/${role.id}/rights/${id}`)
       if(res.meta.status!==200) return this.$message.error('删除权限失败')

      role.children=res.data;
    },
    //分配权限
    async clickSettingDialog(role){
      this.roleId=role.id;

      var {data:res}=await this.$http.get('rights/tree')
      if(res.meta.status!==200) return this.$message.error('获取权限失败')
      this.rightsList=res.data;
      console.log(this.rightsList)
      //调用
      this.getLeafKeys(role,this.defKeys)

      this.settingDialog=true;
    },
    //获取该有的权限
    getLeafKeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getLeafKeys(item,arr)
      })
    },
    //监听对话框关闭
    settingDialogClose(){
      this.defKeys=[]
    },
    //点击权限授权
    async sllotRingts(){
      var Keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      var strr=Keys.join(',');
      var {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:strr})
      console.log(res)
      if(res.meta.status!==200) return this.$message.error('授权失败')
      this.$message.success('授权成功')
      this.settingDialog=false;
      this.getRolesList();
    },
    //点击增加角色按钮
    clickAddRole(){
      this.addRoleDialog=true
    },
    //监听提交角色表单
    submitAddRoleForm(){
      this.$refs.addRole.validate(async valid=>{
        if(!valid){
          return this.$message.info('表单验证不通过')
        }
        //发送请求
        var {data:res}=await this.$http.post('roles',this.addRoleForm)
        if(res.meta.status!==201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        this.getRolesList();
        this.addRoleDialog=false;
      })
    },
    closeAddRoleDialog(){
      this.addRoleForm={};
      this.$refs.addRole.resetFields();
    },
    //编辑角色
    editRole(role){
      this.roleInfo=role;
      this.editRoleDialog=true
    },
    //提交编辑角色
    submitEditRole(){
      this.$refs.editRole.validate(async valid=>{
        if(!valid) return this.$message.error('更新失败')
        //请求
        var {data:res}=await this.$http.put('roles/'+this.roleInfo.id,this.roleInfo);
        if(res.meta.status!==200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.getRolesList();
        this.editRoleDialog=false;
      })
    },
    //监听edit关闭
    closeEditDialog(){
      this.getRolesList();
    },
    //删除角色
    async deleteRole(id){
      console.log(id)
       var confirm=await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirm!=='confirm'){
          this.$message.info('已取消删除')
        }
        var {data:res}=await this.$http.delete('roles/'+id);
        if(res.meta.status!==200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getRolesList();
    }
  },
};
</script>
<style lang="less" scoped>
.borderTop{
  border-top: 1px solid #eee;
}
.borderBottom{
  border-bottom: 1px solid #eee;
}
.el-tag{
  margin: 15rpx;
}
.navCen{
  display: flex;
  align-items: center;
}
</style>